const { Sequelize } = require('sequelize');
// 注意：这里需要模拟appInfo参数来获取配置
const configFn = require('./config/config.default.js');
const appConfig = configFn({ name: 'lingxi-system' });

// 创建数据库连接
const sequelize = new Sequelize(appConfig.sequelize.database, appConfig.sequelize.username, appConfig.sequelize.password, {
  host: appConfig.sequelize.host,
  port: appConfig.sequelize.port,
  dialect: appConfig.sequelize.dialect,
  timezone: appConfig.sequelize.timezone,
  define: appConfig.sequelize.define,
  logging: false, // 关闭SQL日志
});

async function checkTables() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查特定表
    const salesOrdersExists = await sequelize.getQueryInterface().describeTable('sales_orders').then(() => true).catch(() => false);
    const salesOrderItemsExists = await sequelize.getQueryInterface().describeTable('sales_order_items').then(() => true).catch(() => false);
    
    console.log('sales_orders 表是否存在:', salesOrdersExists);
    console.log('sales_order_items 表是否存在:', salesOrderItemsExists);
    
    if (salesOrdersExists) {
      const ordersCount = await sequelize.query('SELECT COUNT(*) as count FROM sales_orders', { type: sequelize.QueryTypes.SELECT });
      console.log('sales_orders 表中的记录数:', ordersCount[0].count);
    }
    
    if (salesOrderItemsExists) {
      const itemsCount = await sequelize.query('SELECT COUNT(*) as count FROM sales_order_items', { type: sequelize.QueryTypes.SELECT });
      console.log('sales_order_items 表中的记录数:', itemsCount[0].count);
    }
    
    // 检查插件数据表
    const pluginBatchesExists = await sequelize.getQueryInterface().describeTable('plugin_data_batches').then(() => true).catch(() => false);
    const pluginItemsExists = await sequelize.getQueryInterface().describeTable('plugin_data_items').then(() => true).catch(() => false);
    
    console.log('plugin_data_batches 表是否存在:', pluginBatchesExists);
    console.log('plugin_data_items 表是否存在:', pluginItemsExists);
    
    if (pluginBatchesExists) {
      const batchesCount = await sequelize.query('SELECT COUNT(*) as count FROM plugin_data_batches', { type: sequelize.QueryTypes.SELECT });
      console.log('plugin_data_batches 表中的记录数:', batchesCount[0].count);
    }
    
    if (pluginItemsExists) {
      const itemsCount = await sequelize.query('SELECT COUNT(*) as count FROM plugin_data_items', { type: sequelize.QueryTypes.SELECT });
      console.log('plugin_data_items 表中的记录数:', itemsCount[0].count);
    }
    
  } catch (error) {
    console.error('检查表时出错:', error);
  } finally {
    await sequelize.close();
  }
}

checkTables();